let fs = require('fs');
let path = require('path');
let express = require('express');
let WebSocket = require('ws');
let webS = new WebSocket.Server({host: 'localhost', port: 9001});
webS.on('connection', (client) => {
    client.onmessage = function(event){
        client.send('res: ' + event.data + ` ${Date.now()}`);
    };
})

let cookieParser = require('cookie-parser');// 格式化cookie的插件
{
    let app = express();
    app.use(cookieParser());
    app.get('/user/info', userInfo(9001));
    app.post('/user/info', userInfo(9001));
    app.post('/other/test', userInfo(9001));

    app.get('/login', (req, res) => {
        if (!req.cookies.userId) {// 使用了cookie-parser插件，所以可以这样使用：cookies.userId
            res.cookie('userId', Math.random());
        }
        let query = req.query;
        if (query.username && query.password) {
            for (let key in req.query) {
                res.cookie(key, req.query[key]);
            }
        }
        res.send(req.query);
    });

    app.get('/get-png', (req, res) => {
        const filePath = path.resolve(__dirname, './test.png');
        // 给客户端返回一个文件流

        // 格式必须为 binary，否则会出错
        // 创建文件可读流
        const cs = fs.createReadStream(filePath);
        cs.pipe(res);
    });

    app.listen(9001, () => { });
}

{
    let app = express();
    app.use(cookieParser());
    app.get('/user/info', userInfo(9002));
    app.post('/user/info', userInfo(9002));
    app.post('/other/test', userInfo(9002));

    app.get('/get-png', (req, res) => {
        const filePath = path.resolve(__dirname, './test.png');
        // 创建文件可读流
        const cs = fs.createReadStream(filePath);
        cs.pipe(res);
    });

    app.listen(9002, () => { });
}
function userInfo(port) {
    return function (req, res) {
        if (!req.cookies.userId) {// 使用了cookie-parser插件，所以可以这样使用：cookies.userId
            res.cookie('userId', Math.random());
        }
        for (let key in req.query) {
            res.cookie(key, req.query[key]);
        }
        let sendData = Object.assign({message: '成功'}, req.query);
        sendData.port = port;
        sendData.stemp = Date.now();
        res.send(sendData);
    };
}
